<template>
  <div class="statistics">
    <div class="page-header">
      <h1>数据统计</h1>
      <el-button type="primary" @click="refreshData">
        <el-icon><Refresh /></el-icon>
        刷新数据
      </el-button>
    </div>

    <!-- 总览统计 -->
    <el-row :gutter="20" style="margin-bottom: 24px;">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon" size="32" color="#409EFF">
              <UserFilled />
            </el-icon>
            <div class="stat-info">
              <div class="stat-number">{{ dashboardStats.total_users || 0 }}</div>
              <div class="stat-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon" size="32" color="#67C23A">
              <Document />
            </el-icon>
            <div class="stat-info">
              <div class="stat-number">{{ dashboardStats.total_exams || 0 }}</div>
              <div class="stat-label">总考试数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon" size="32" color="#E6A23C">
              <TrendCharts />
            </el-icon>
            <div class="stat-info">
              <div class="stat-number">{{ dashboardStats.total_scores || 0 }}</div>
              <div class="stat-label">总成绩数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon" size="32" color="#F56C6C">
              <Warning />
            </el-icon>
            <div class="stat-info">
              <div class="stat-number">{{ dashboardStats.active_sessions || 0 }}</div>
              <div class="stat-label">活跃会话</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <!-- 用户统计 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>用户统计</span>
              <el-button type="text" @click="showUserDetail = !showUserDetail">
                {{ showUserDetail ? '收起' : '详情' }}
              </el-button>
            </div>
          </template>
          <div class="chart-container">
            <div ref="userChartRef" style="height: 300px;"></div>
          </div>
          <div v-if="showUserDetail" class="detail-stats">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="管理员">{{ userStats.admins || 0 }}</el-descriptions-item>
              <el-descriptions-item label="教师">{{ userStats.teachers || 0 }}</el-descriptions-item>
              <el-descriptions-item label="学生">{{ userStats.students || 0 }}</el-descriptions-item>
              <el-descriptions-item label="活跃用户">{{ userStats.active_users || 0 }}</el-descriptions-item>
              <el-descriptions-item label="新增用户(今日)">{{ userStats.new_users_today || 0 }}</el-descriptions-item>
              <el-descriptions-item label="新增用户(本周)">{{ userStats.new_users_week || 0 }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>

      <!-- 考试统计 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>考试统计</span>
              <el-button type="text" @click="showExamDetail = !showExamDetail">
                {{ showExamDetail ? '收起' : '详情' }}
              </el-button>
            </div>
          </template>
          <div class="chart-container">
            <div ref="examChartRef" style="height: 300px;"></div>
          </div>
          <div v-if="showExamDetail" class="detail-stats">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="草稿考试">{{ examStats.draft_exams || 0 }}</el-descriptions-item>
              <el-descriptions-item label="已发布考试">{{ examStats.published_exams || 0 }}</el-descriptions-item>
              <el-descriptions-item label="进行中考试">{{ examStats.ongoing_exams || 0 }}</el-descriptions-item>
              <el-descriptions-item label="已完成考试">{{ examStats.completed_exams || 0 }}</el-descriptions-item>
              <el-descriptions-item label="今日考试">{{ examStats.exams_today || 0 }}</el-descriptions-item>
              <el-descriptions-item label="平均题目数">{{ examStats.avg_questions || 0 }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 成绩统计 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>成绩统计</span>
              <el-button type="text" @click="showScoreDetail = !showScoreDetail">
                {{ showScoreDetail ? '收起' : '详情' }}
              </el-button>
            </div>
          </template>
          <div class="chart-container">
            <div ref="scoreChartRef" style="height: 300px;"></div>
          </div>
          <div v-if="showScoreDetail" class="detail-stats">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="平均分">{{ scoreStats.average_score || 0 }}</el-descriptions-item>
              <el-descriptions-item label="最高分">{{ scoreStats.highest_score || 0 }}</el-descriptions-item>
              <el-descriptions-item label="最低分">{{ scoreStats.lowest_score || 0 }}</el-descriptions-item>
              <el-descriptions-item label="及格率">{{ scoreStats.pass_rate || 0 }}%</el-descriptions-item>
              <el-descriptions-item label="优秀率">{{ scoreStats.excellent_rate || 0 }}%</el-descriptions-item>
              <el-descriptions-item label="今日成绩">{{ scoreStats.scores_today || 0 }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>

      <!-- 系统统计 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>系统统计</span>
              <el-button type="text" @click="showSystemDetail = !showSystemDetail">
                {{ showSystemDetail ? '收起' : '详情' }}
              </el-button>
            </div>
          </template>
          <div class="chart-container">
            <div ref="systemChartRef" style="height: 300px;"></div>
          </div>
          <div v-if="showSystemDetail" class="detail-stats">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="系统运行时间">{{ systemStats.uptime || '0天' }}</el-descriptions-item>
              <el-descriptions-item label="CPU使用率">{{ systemStats.cpu_usage || '0%' }}</el-descriptions-item>
              <el-descriptions-item label="内存使用率">{{ systemStats.memory_usage || '0%' }}</el-descriptions-item>
              <el-descriptions-item label="磁盘使用率">{{ systemStats.disk_usage || '0%' }}</el-descriptions-item>
              <el-descriptions-item label="API请求量">{{ systemStats.api_requests || 0 }}</el-descriptions-item>
              <el-descriptions-item label="错误率">{{ systemStats.error_rate || '0%' }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 活动时间线 -->
    <el-card style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>最近活动</span>
          <el-button type="text" @click="loadRecentActivities">
            <el-icon><Refresh /></el-icon>
          </el-button>
        </div>
      </template>
      <el-timeline>
        <el-timeline-item
          v-for="activity in recentActivities"
          :key="activity.id"
          :timestamp="formatDateTime(activity.timestamp)"
          :type="getActivityType(activity.type)"
        >
          <div class="activity-content">
            <div class="activity-title">{{ activity.title }}</div>
            <div class="activity-description">{{ activity.description }}</div>
            <div class="activity-user">{{ activity.user }} · {{ activity.module }}</div>
          </div>
        </el-timeline-item>
      </el-timeline>
      <el-empty v-if="recentActivities.length === 0" description="暂无活动记录" />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import api from '../api';
import { ElMessage } from 'element-plus';
import { Refresh, UserFilled, Document, TrendCharts, Warning } from '@element-plus/icons-vue';

// 统计数据
const dashboardStats = ref({});
const userStats = ref({});
const examStats = ref({});
const scoreStats = ref({});
const systemStats = ref({});
const recentActivities = ref([]);

// 图表引用
const userChartRef = ref();
const examChartRef = ref();
const scoreChartRef = ref();
const systemChartRef = ref();

// 显示状态
const showUserDetail = ref(false);
const showExamDetail = ref(false);
const showScoreDetail = ref(false);
const showSystemDetail = ref(false);

const formatDateTime = (datetime) => {
  return new Date(datetime).toLocaleString('zh-CN');
};

const getActivityType = (type) => {
  const typeMap = {
    'login': 'primary',
    'create': 'success',
    'update': 'warning',
    'delete': 'danger',
    'error': 'danger'
  };
  return typeMap[type] || 'info';
};

const loadDashboardStats = async () => {
  try {
    const response = await api.statistics.getDashboardStats();
    dashboardStats.value = response.data;
  } catch (error) {
    console.error('加载仪表板统计失败:', error);
  }
};

const loadUserStats = async () => {
  try {
    const response = await api.statistics.getUserStats();
    userStats.value = response.data;
  } catch (error) {
    console.error('加载用户统计失败:', error);
  }
};

const loadExamStats = async () => {
  try {
    const response = await api.statistics.getExamStats();
    examStats.value = response.data;
  } catch (error) {
    console.error('加载考试统计失败:', error);
  }
};

const loadScoreStats = async () => {
  try {
    const response = await api.statistics.getScoreStats();
    scoreStats.value = response.data;
  } catch (error) {
    console.error('加载成绩统计失败:', error);
  }
};

const loadSystemStats = async () => {
  try {
    const response = await api.statistics.getSystemStats();
    systemStats.value = response.data;
  } catch (error) {
    console.error('加载系统统计失败:', error);
  }
};

const loadRecentActivities = async () => {
  try {
    const response = await api.logs.getLogs({ limit: 10 });
    recentActivities.value = response.data.items || response.data.slice(0, 10);
  } catch (error) {
    console.error('加载最近活动失败:', error);
  }
};

const initCharts = () => {
  // 这里应该使用实际的图表库如 ECharts
  // 为了简化，这里只显示占位符
  console.log('初始化图表...');
};

const refreshData = async () => {
  ElMessage.info('正在刷新数据...');
  await Promise.all([
    loadDashboardStats(),
    loadUserStats(),
    loadExamStats(),
    loadScoreStats(),
    loadSystemStats(),
    loadRecentActivities()
  ]);
  await nextTick();
  initCharts();
  ElMessage.success('数据刷新成功');
};

onMounted(async () => {
  await refreshData();
});
</script>

<style scoped>
.statistics {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  margin-right: 16px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 16px;
}

.chart-container::before {
  content: '图表加载中...';
  color: #909399;
  font-size: 14px;
}

.detail-stats {
  margin-top: 16px;
}

.activity-content {
  line-height: 1.6;
}

.activity-title {
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.activity-description {
  color: #606266;
  margin-bottom: 4px;
}

.activity-user {
  font-size: 12px;
  color: #909399;
}
</style>